﻿using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Vanara.PInvoke;
using Size = OpenCvSharp.Size;

namespace OperateMouse
{
    internal class SlideRecognition
    {
        public void Check()
        {
            Mat image = Cv2.ImRead("captcha.png");

            int imageWidth = image.Width;
            int imageHeight = image.Height;

            Mat blurredImage = new Mat();
            Cv2.GaussianBlur(image, blurredImage, new Size(5, 5), 0);

            Mat cannyImage = new Mat();
            Cv2.Canny(blurredImage, cannyImage, 200, 450);

            HierarchyIndex[] hierarchy;
            Cv2.FindContours(cannyImage, out var contours, out hierarchy, RetrievalModes.CComp, ContourApproximationModes.ApproxSimple);

            double[] contourAreaThreshold = GetContourAreaThreshold(imageWidth, imageHeight);
            double[] arcLengthThreshold = GetArcLengthThreshold(imageWidth, imageHeight);
            double[] offsetThreshold = GetOffsetThreshold(imageWidth);

            int offset = -1;
            foreach (var contour in contours)
            {
                Rect rect = Cv2.BoundingRect(contour);
                double contourArea = Cv2.ContourArea(contour);
                double arcLength = Cv2.ArcLength(contour, true);

                if (contourArea > contourAreaThreshold[0] && contourArea < contourAreaThreshold[1] &&
                    arcLength > arcLengthThreshold[0] && arcLength < arcLengthThreshold[1] &&
                    rect.X > offsetThreshold[0] && rect.X < offsetThreshold[1])
                {
                    Cv2.Rectangle(image, rect, new Scalar(0, 0, 255), 2);
                    offset = rect.X;
                }
            }

            Cv2.ImWrite("image_label.png", image);
            Console.WriteLine("Offset: " + offset);
        }
        private static double[] GetContourAreaThreshold(int imageWidth, int imageHeight)
        {
            double contourAreaMin = (imageWidth * 0.15) * (imageHeight * 0.25) * 0.8;
            double contourAreaMax = (imageWidth * 0.15) * (imageHeight * 0.25) * 1.2;
            return new double[] { contourAreaMin, contourAreaMax };
        }

        private static double[] GetArcLengthThreshold(int imageWidth, int imageHeight)
        {
            double arcLengthMin = ((imageWidth * 0.15) + (imageHeight * 0.25)) * 2 * 0.8;
            double arcLengthMax = ((imageWidth * 0.15) + (imageHeight * 0.25)) * 2 * 1.2;
            return new double[] { arcLengthMin, arcLengthMax };
        }

        private static double[] GetOffsetThreshold(int imageWidth)
        {
            double offsetMin = 0.2 * imageWidth;
            double offsetMax = 0.85 * imageWidth;
            return new double[] { offsetMin, offsetMax };
        }
    }
}
